var organizationName = "";

//define callback for extjs ready event
Ext.onReady(function() {
	Ext.QuickTips.init();

    //handler for ajax request for organization title
    var getTitleSuccessOrFail = function(response,opts){
        var responseJson = Ext.decode(response.responseText);
        if (responseJson.success==="true"){
            organizationName = responseJson.name;
            //tree panel
            var tree = {
                xtype      : 'treepanel',
                id		   : 'treepanel',
                border	   : false,
                autoScroll : true,
                animate    : false,
                loader     : new Ext.tree.TreeLoader({
                    url :  'data/getTree'
                }),
                root       : {
                    text     : organizationName,
                    id       : organizationName,
                    type	 : 'root',
                    nodeType : 'async',
                    expanded : true
                },
                listeners   : {
                    contextmenu : onCtxMenu,
                    click: function(node, eventObj){
                        showInfo(node);
                    },
                    load: function(node, eventObj){
                        var rootNode = Ext.getCmp('treepanel').getRootNode();
                        if (node == rootNode)
                            showInfo(rootNode);
                    }
                }
            }

            //main viewport with two regions
            new Ext.Viewport({
                id       : 'mainViewportId',
                layout   : 'border',
                defaults : {
                    frame  : false,
                    split  : true
                },
                items : [
                    {
                        width		 : 300,
                        title        : 'Organization structure',
                        region       : 'west',
                        collapsible  : true,
                        collapseMode : 'mini',
                        items : tree
                    },
                    {
                        xtype  : 'container',
                        region : 'center',
                        layout : 'fit',
                        id     : 'centerRegion',
                        autoEl : {},
                        items  : {
                            title : 'Information panel',
                            xtype : 'panel',
                            id    : 'infoPanelId',
                            frame : true
                        }
                    }
                ]
            });
        }
        else {
            var message = '';
            if (responseJson.error)
                message = responseJson.error;
            else
            message = 'Fetch organization title error!';
            Ext.Msg.alert('Error',message);
        }
    }

    //request for organization title
    Ext.Ajax.request({
        url    : 'data/getTitle',
        success : getTitleSuccessOrFail,
        failure : getTitleSuccessOrFail
    });

    //build context menu for tree nodes
    var buildCtxMenu = function() {
        return new Ext.menu.Menu({
            items: [
                {
                    itemId  : 'add',
                    handler : onAddNode
                },
                {
                    itemId  : 'delete',
                    handler : onDelete
                }
            ]
        });
    }

    //add node handler for treepanel context menu
	var onAddNode = function() {
		var treePanel =  Ext.getCmp('treepanel');
		var selNode = treePanel.getSelectionModel().getSelectedNode();

        //create window with add form
        addNodeWindow(selNode);
	}

    //delete node handler for treepanel context menu
    var onDelete = function() {
        var treePanel =  Ext.getCmp('treepanel');
        var selNode = treePanel.getSelectionModel().getSelectedNode();
        if (selNode) {
            Ext.MessageBox.confirm(
                'Are you sure?',
                'Please confirm the deletion of ' + selNode.attributes.text,
                onConfirmDelete
            )
        }
    }

    //right button handler for tree panel
	var onCtxMenu = function(node, evtObj) {
        node.select();
        evtObj.stopEvent();
        showInfo(node);

        if (! this.ctxMenu) {
            this.ctxMenu = buildCtxMenu();
        }

        var ctxMenu    = this.ctxMenu;
        var addItem    = ctxMenu.getComponent('add');
        var deleteItem = ctxMenu.getComponent('delete');

        if (node.id == organizationName) {
            addItem.setText('Add Department');
            deleteItem.setText('Can\'t delete a company');
            addItem.enable();
            deleteItem.disable();
        }
        else if (node.id.match('Department_')) {
            addItem.setText('Add Project');
            deleteItem.setText('Delete Department');
            addItem.enable();
            deleteItem.enable();
        }
        else if (node.id.match('Project_')){
            addItem.setText('Add Employee');
            deleteItem.setText('Delete Project');
            addItem.enable();
            deleteItem.enable();
        }
        else if (node.id.match('Employee_')){
            addItem.setText('Can\'t add node');
            deleteItem.setText('Delete Employee');
            addItem.disable();
            deleteItem.enable();
        }
        else {
            addItem.setText('');
            deleteItem.setText('');
            addItem.disable();
            deleteItem.disable();
        }
        ctxMenu.showAt(evtObj.getXY()) ;
    }
});

